package com.huayue.dao;

import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.huayue.entity.Department;
import com.huayue.util.PageHelper;
import com.mysql.DBHelper;

/**
 * 部门
 * 
 */
@Component
public class DepartmentDao implements BaseDao<Department> {
    @Override
    public int insert(Department entity) {
        return DBHelper.executeUpdate("insert into department (parentid, name,remark) values (?, ?,?);",
            entity.getParentid(), entity.getName(), entity.getRemark());
    }

    @Override
    public int update(Department entity) {
        return DBHelper.executeUpdate("update department set parentid=?,name=?,remark=? where id=?",
            entity.getParentid(), entity.getName(), entity.getRemark(), entity.getId());
    }

    @Override
    public int delete(Department entity) {
        return DBHelper.executeUpdate("update department set is_deleted=1 where id=?", entity.getId());
    }

    @Override
    public List<Map<String, Object>> findAll(Object... obj) {
        return DBHelper.executeQuery("select * from department where is_deleted=0");
    }

    @Override
    public List<Map<String, Object>> findPage(PageHelper page, Object... obj) {
        String sql =
            "select a.name parentname,b.* from department a right JOIN department b on b.parentid=a.id where b.is_deleted=0 ";
        if (obj[0] != null & "0".equals(obj[0].toString())) {
            sql += " and b.parentid=0";
        } else if (obj[0] != null & "1".equals(obj[0].toString())) {
            sql += " and b.parentid!=0";
        }
        return DBHelper.executeQuery(sql + " limit ?,? ", page.getBegin(), page.getPageSize());
    }

    @Override
    public Map<String, Object> findOne(Department entity) {

        return DBHelper.executeQuery(
            "select a.name parentname,b.* from department a right JOIN department b on b.parentid=a.id where b.is_deleted=0 and b.id=? ",
            entity.getId()).get(0);
    }

    @Override
    public int count(Object... obj) {
        String sql =
            "select count(*) counts from department a right JOIN department b on b.parentid=a.id where b.is_deleted=0 ";
        if (obj[0] != null & "0".equals(obj[0].toString())) {
            sql += " and b.parentid=0";
        } else if (obj[0] != null & "1".equals(obj[0].toString())) {
            sql += " and b.parentid!=0";
        }
        return Integer.valueOf(DBHelper.executeQuery(sql).get(0).get("counts").toString());
    }

    public List<Map<String, Object>> findAllTopDepartment() {
        return DBHelper.executeQuery("select * from department where is_deleted=0 and parentid=0 or parentid=1");
    }
}
